package com.taomus.mytools.lang.jruby;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Objects;

import org.jruby.Ruby;
import org.jruby.RubyRuntimeAdapter;
import org.jruby.javasupport.JavaEmbedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taomus.mytools.helper.stream.StreamHelper;
import com.taomus.mytools.lang.ILanguageHelper;
import com.taomus.mytools.lang.IMethod;

public class JRubyHelper extends ILanguageHelper{
	private static Logger logger = LoggerFactory.getLogger(JRubyHelper.class);
	
	@Override
	public void putPath(String name, String path) {
		if(!this.filePool.containsKey(name)){
			logger.debug(path);
			this.filePool.put(name, path);
		}
		
	}

	@Override
	public IMethod newInstance(String name){
		String filename = null;
		if(name.endsWith(".rb")){
			filename = name;
			name = name.substring(name.lastIndexOf("/")+1);
			name = name.replace(".rb", "");
		}else{
			filename = this.filePool.get(name);
		}
		if(filename != null){
			InputStream input = StreamHelper.getInputStreamByFileName(filename);
		    ArrayList<String> loadPaths = new ArrayList<String>();  
			loadPaths.add("/root/.jruby/lib/ruby/1.8");  
			loadPaths.add("/root/.jruby/lib/ruby/site_ruby/1.8");  
			Ruby runtime = JavaEmbedUtils.initialize(loadPaths);
			RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();
			return new JRubyMethod(name,runtime,evaler,input,filename);
		}
		return null;
	}
	

	@Override
	public Class<?> getClass(String name) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
}
